import React, { Component, Suspense } from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import { connect } from "dva";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import PageLoading from "@/components/PageLoading";
import { List, Button, Card, Form, Input, message, Select, Spin, Tag, Icon, Modal, Tooltip } from "antd";
import moment from "moment";
import styles from "./index.less";
import { getTagList, getTemplateList, delTemplate } from "@/services/modelInstruction";
import AddInstructions from "./add";
import u172 from '@/assets/modelInstruction/u172.svg';

class InstructList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tagList: [],
            list: [],
            total: 0,
            queryData: {
                key: undefined,
                current: 1,
                size: 16,
            }
        }
    };

    componentDidMount() {
        if (this.props.onRef) {
            this.props.onRef(this);
        };
        // this.getTagList();
        this.getList();
    }

    getTagList = async () => {
        let res = await getTagList();
        console.log(res);
        this.setState({ tagList: res, })
    }

    getList = async () => {
        const { queryData } = this.state;
        const { categoryId, currentUser } = this.props;
        let obj = {
            ...queryData,
            categoryId,
            urlPrefix: currentUser.tenantId == "1" ? "admin" : undefined
        };
        let res = await getTemplateList(obj);
        console.log(res);
        this.setState({ list: res.records, total: res.total });
    }

    queryByPage = () => {
        let { queryData } = this.state;
        let userInfo = this.props.form.getFieldsValue();
        console.log(userInfo);
        queryData.current = 1;
        queryData.key = userInfo.key;
        this.setState({ queryData }, () => this.getList())
    }

    fenye = (page) => {
        let { queryData } = this.state;
        queryData.current = page;
        this.setState({ queryData }, () => this.getList());
    };

    addInstructions = () => {
        if (this.addInstructionRef) {
            this.addInstructionRef._init_();
        }
    }

    editInstructions = row => {
        if (this.addInstructionRef) {
            this.addInstructionRef._init_(row);
        }
    }

    delInstruct = id => {
        Modal.confirm({
            content: formatMessage({ id: 'personalizedInstructionLibrary.confirmDeleteInstruction' }),
            okText: formatMessage({ id: 'personalizedInstructionLibrary.delete' }),
            okType: 'danger',
            cancelText: formatMessage({ id: 'personalizedInstructionLibrary.cancel' }),
            maskStyle: { zIndex: 99999 },
            zIndex: 999999,
            onOk: async () => {
                let res = await delTemplate({ id });
                console.log(res);
                if (res.code === 0) {
                    message.success(formatMessage({ id: 'personalizedInstructionLibrary.operationSuccess' }));
                    this.getList();
                }
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }

    render() {
        const { list, total, queryData, tagList } = this.state;
        const { categoryList, categoryId } = this.props;
        const { getFieldDecorator } = this.props.form;

        return (
            <div style={{ paddingRight: 12 }}>
                <div className={styles['instruct-flex']} style={{ marginBottom: 20 }}>
                    <Form layout="inline">
                        <Form.Item>
                            {getFieldDecorator("key")(<Input placeholder={formatMessage({ id: 'personalizedInstructionLibrary.searchKey' })} style={{ width: '240px' }} />)}
                        </Form.Item>
                        {/* <Form.Item>
                            {getFieldDecorator("tagId")(
                                <Select allowClear placeholder="标签筛选【多选】" style={{ width: '240px' }} mode="multiple">
                                    {tagList.map((item) => {
                                        return (
                                            <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                        );
                                    })}
                                </Select>
                            )}
                        </Form.Item> */}
                        <Form.Item>
                            <Button type="primary" onClick={this.queryByPage}>{formatMessage({ id: 'personalizedInstructionLibrary.query' })}</Button>
                        </Form.Item>
                    </Form>
                    <Button type="primary" onClick={this.addInstructions}>{formatMessage({ id: 'personalizedInstructionLibrary.add' })}</Button>
                </div>
                <List
                    rowKey='id'
                    pagination={{
                        onChange: (page) => this.fenye(page),
                        current: queryData.current,
                        pageSize: 16,
                        total: parseInt(total),
                        showQuickJumper: true,
                    }}
                    grid={{ gutter: 16, column: 4 }}
                    dataSource={list}
                    renderItem={(item) => (
                        <List.Item key={item.id}>
                            <Card hoverable className={styles.cardOutBox} bordered={false} bodyStyle={{ padding: 18 }}>
                                <div className={styles.cardBox}>
                                    <img src={item.imgUrl} className={styles.titleImg} />
                                    <div>
                                        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                                            <div className={styles.title}>{item.title}</div>
                                            <div>
                                                <Icon type="delete" onClick={() => this.delInstruct(item.id)} />
                                                <Icon type="form" style={{ marginLeft: 6 }} onClick={() => this.editInstructions(item)} />
                                            </div>
                                        </div>
                                        <Tooltip placement="bottom" title={<div dangerouslySetInnerHTML={{ __html: item.content }}></div>}>
                                            <div className={`${styles['card-item-list']} ${styles['m-b-10']}`}>
                                                <p
                                                    dangerouslySetInnerHTML={{ __html: item.content }}
                                                    style={{
                                                        WebkitBoxOrient: 'vertical',
                                                        minHeight: '50px',
                                                    }}
                                                />
                                            </div>
                                        </Tooltip>
                                        <div className={styles.footer}>
                                            <div>{moment(item.createTime).format('YYYY-MM-DD')}</div>
                                            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                                                <Icon type="fire" theme="twoTone" twoToneColor="#F5310D" />
                                                <span>{item.useCount}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </Card>
                        </List.Item>
                    )}
                />
                <AddInstructions
                    onRef={ref => this.addInstructionRef = ref}
                    getList={this.getList}
                    categoryId={categoryId}
                    tagList={tagList}
                    categoryList={categoryList}
                />
            </div>
        );
    }
}

export default connect(({ user }) => ({
    currentUser: user.currentUser,
}))(Form.create()(InstructList));
